package com.cqc.jdk8.Jutil.concurrent.threadPoolExecutor.base;

import java.sql.SQLOutput;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * @author cui
 * @date 2023/11/10 22:21
 * @description
 **/
public class ThreadPoolTest2 {

    /**
     * 线程池的执行流程
     * 核心线程数  》  队列   》 最大线程数
     */
    public static void main2(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2,
                3,
                60,
                TimeUnit.SECONDS,
                //new LinkedBlockingQueue<>(1)
                new ArrayBlockingQueue<>(1)
        );

        System.out.println("开始：" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        executor.submit(new Task11());
        executor.submit(new Task12());
        executor.submit(new Task13());
        executor.submit(new Task14());
        //当 maximumPoolSize + queue.capacity > 任务数量 时，执行拒绝策略。
        //抛出异常 java.util.concurrent.RejectedExecutionException
        executor.submit(new Task15());


        executor.shutdown();
    }

    /**
     * 再拒绝策略中，如果不抛出异常，或调用主线程，那么主线程就不知道线程池的情况，调用get会一直阻塞主线程。
     * @param args
     */
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ThreadPoolExecutor executor= new ThreadPoolExecutor(
                1,
                1,
                0,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1),
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        System.out.println("没有多余的线程了");
                        throw new RuntimeException();//抛异常不会唤醒主线程。
                    }
                }
                //new ThreadPoolExecutor.DiscardPolicy()
                //new ThreadPoolExecutor.DiscardOldestPolicy()//丢弃后，还会尝试执行该任务
                //new ThreadPoolExecutor.CallerRunsPolicy()//只有这种策略会唤醒主线程。
                //new ThreadPoolExecutor.AbortPolicy()
        );
        try {
            System.out.println("开始：" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            Future<Integer> future21 = executor.submit(new TaskCallable21());
            Future<Integer> future22 = executor.submit(new TaskCallable22());
            Future<Integer> future23 = executor.submit(new TaskCallable23());

            Integer i21 = future21.get();
            Integer i22 = future22.get();
            Integer i23 = future23.get();
        } finally {
            executor.shutdown();
            System.out.println("关闭线程池");
        }


    }


}
